package com.jgp.third.pay.controller;

import com.jgp.sys.controller.JGPBackController;
import com.jgp.common.utils.ReflectUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * 项目   jgp-cloud-parent
 * 作者   loufei
 * 时间   2018/10/24
 */
@RestController
@RequestMapping("/third/pay/aliPayApiController")
public class AliPayApiController extends JGPBackController {
    
    private static Logger logger = LoggerFactory.getLogger(AliPayController.class);
    
    @Value("${jgp.pay.callback-class}")
    private String callbackClass;
    
    @RequestMapping("payNotify")
    public void payNotify(HttpServletRequest request,HttpServletResponse response){
        String notifyType = request.getParameter("notify_type");
        Map<String, Object> params = new HashMap<>();
        Map<String, Object> origin = new HashMap<>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
            origin.put(name, valueStr);
        }
        params.put("origin", origin);
        if("trade_status_sync".equals(notifyType)){
            String orderNo = request.getParameter("out_trade_no");
            String no = request.getParameter("trade_no");
            String money = request.getParameter("total_amount");
            String sellerId = request.getParameter("seller_id");
            params.put("notifyType", notifyType);
            params.put("orderNo", orderNo);
            params.put("no", no);
            params.put("money", money);
            params.put("sellerId", sellerId);
            try {
                String passbackParams = request.getParameter("passback_params");
                if(StringUtils.isNotBlank(passbackParams)){
                    String jsonParams = URLDecoder.decode(passbackParams, "utf-8");
                    params.put("jsonParams", jsonParams);
                }
            } catch (IOException e) {
                logger.error("解析jsonParams异常", e);
            }
        }else if("batch_trans_notify".equals(notifyType)){
            params.put("notifyType", notifyType);
            params.put("batchNo",request.getParameter("batch_no"));
            try {
                params.put("successDetails",new String(request.getParameter("success_details").getBytes("ISO-8859-1"),"UTF-8"));
                params.put("failDetails",new String(request.getParameter("fail_details").getBytes("ISO-8859-1"),"UTF-8"));
            } catch (UnsupportedEncodingException e) {
                logger.error("获取批量付款数据中转账信息失败", e);
            }
        }
    
        try {
            if (StringUtils.isNotBlank(callbackClass)) {
                ReflectUtil.invoke(callbackClass, "payNotice", new Class[]{Map.class} , params);
            }
            response.getWriter().print("success");
        } catch (ClassNotFoundException | InvocationTargetException | IllegalAccessException |
                InstantiationException e) {
            logger.error("回调类异常，检查回调类是否配置正常", e);
        } catch (IOException e) {
            logger.error("写回支付宝\"通知成功\"失败!",e);
        }
    
    
    }
}
